package com.qingcheng.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.qingcheng.pojo.goods.Category;
import com.qingcheng.pojo.goods.Sku;
import com.qingcheng.pojo.order.OrderItem;
import com.qingcheng.service.goods.CategoryService;
import com.qingcheng.service.goods.SkuService;
import com.qingcheng.service.order.CartService;
import com.qingcheng.service.order.PreferentialService;
import com.qingcheng.util.CacheKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

public class CartServiceImpl implements CartService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Reference
    private SkuService skuService;
    @Reference
    private CategoryService categoryService;
    @Reference
    private PreferentialService preferentialService;
    @Override
    public List<Map<String, Object>> findCartList(String username) {
        List<Map<String,Object>> carList = (List<Map<String, Object>>) redisTemplate.boundHashOps(CacheKey.CART_List).get(username);
        if (carList==null){
            carList=new ArrayList<>();
        }
        return carList;
    }

    @Override
    public void addItem(String username, String skuId, Integer num) {
        //1:查询购物车
        List<Map<String, Object>> cartList = this.findCartList(username);
        boolean flag = false;
        //2:list 循环  skuId==id  购物车的修改 num+   count
        if (cartList.size()>0){
            for (Map map:cartList){
                OrderItem orderItem = (OrderItem) map.get("item");
                if (orderItem.getSkuId()==skuId){
                    //清楚删除的购物车
                    if (orderItem.getNum() <= 0) {
                        //如果数量小于等于0
                        cartList.remove(map);
                        flag =true;
                        break;
                    }
                    orderItem.setNum(orderItem.getNum()+num); //修改数量
                    orderItem.setMoney(orderItem.getPrice()*orderItem.getNum()); //修改价钱 单价*总数量
                    if (orderItem.getNum()==0){
                        orderItem.setWeight(0);
                    }else{
                        int weight = orderItem.getWeight() / orderItem.getNum(); //单个商品的重量
                        orderItem.setWeight(weight * num);
                    }
                    //清除删除的购物车
                    if (orderItem.getNum() <= 0) {
                        //如果数量小于等于0  购物车项删除
                        cartList.remove(map);
                    }
                    //购物车判断是否重复提交
                    flag = true;
                    break;
                }
                //3:skuId!=id orderItem set redis hash

                //从数据库把商品查询出来
                if (flag==false){
                    Sku sku = skuService.findById(skuId);
                    if (sku == null) {
                        throw new RuntimeException("商品不存在");
                    }
                    if (!"1".equals(sku.getStatus())) {
                        throw new RuntimeException("商品状态不合法");
                    }
                    if (num <= 0) {
                        //数量不能为0或负数
                        throw new RuntimeException("商品数量不合法");
                    }
                    OrderItem orderItem1 = new OrderItem();
                    orderItem1.setSkuId(skuId);
                    orderItem1.setSpuId(sku.getSpuId());
                    orderItem1.setNum(num);
                    orderItem1.setImage(sku.getImage());
                    orderItem1.setPrice(sku.getPrice());
                    orderItem1.setName(sku.getName());
                    orderItem1.setMoney(orderItem.getPrice() * num);//金额计算
                    if (sku.getWeight() == null) {
                        sku.setWeight(0);
                    }
                    orderItem.setWeight(sku.getWeight() * num); //重量计算
                    //获取二级分类
                    orderItem1.setCategoryId3(sku.getCategoryId());
                    Category category3 = (Category) redisTemplate.boundHashOps(CacheKey.CATEGROY_TREE).get(sku.getCategoryId());
                    if (category3 == null) {
                        category3 = categoryService.findById(sku.getCategoryId());
                        //根据3级分类id查2级
                        redisTemplate.boundHashOps(CacheKey.CATEGROY_TREE).put(sku.getCategoryId(), category3);
                    }
                    orderItem.setCategoryId2(category3.getParentId());

                    //获取一级分类
                    Category category2 = (Category) redisTemplate.boundHashOps(CacheKey.CATEGROY_TREE).get(category3.getParentId());
                    if (category2 == null) {
                        category2 = categoryService.findById(category3.getParentId());
                        //根据2级分类id查询1级
                        redisTemplate.boundHashOps(CacheKey.CATEGROY_TREE).put(category3.getParentId(), category2);
                    }
                    orderItem.setCategoryId1(category2.getParentId());
                }
                //构建购物车数据结构
                Map cartMap = new HashMap();
                cartMap.put("item", orderItem);
                cartMap.put("checked", true);
                //默认选中
                cartList.add(cartMap);
            }
            //添加购物车信息 购物车只操作redis 没有db 不会放到数据库中
            redisTemplate.boundHashOps(CacheKey.CART_List).put(username,cartList);
            redisTemplate.boundHashOps(CacheKey.CART_List).expire(30, TimeUnit.MINUTES);
        }
    }

    @Override
    public boolean updateChecked(String username, String skuId, boolean checked) {
        //根据用户查询购物车
        List<Map<String, Object>> cartList = this.findCartList(username);
        //循环购物车  找到skuId
        boolean flag=false;
        for (Map map : cartList){
            OrderItem orderItem = (OrderItem) map.get("item"); //拿到循环单条的购物车数据
            if (orderItem.getSkuId().equals(skuId)){
                //修改购物车中 checked = 参数
                map.put("checked",checked);
                flag=true;
                break;
            }

        }
        //更新redis
        if (flag){
            redisTemplate.boundHashOps(CacheKey.CART_List).put(username,cartList);
            redisTemplate.boundHashOps(CacheKey.CART_List).expire(30,TimeUnit.MINUTES);
        }

        return false;
    }

    @Override
    public void deleteCheckedCart(String username) {
        //根据用户查询购物车
        List<Map<String, Object>> cartList = this.findCartList(username).
        stream().filter(bie ->(boolean)bie.get("checked")==false).collect(Collectors.toList());

        //redis
        redisTemplate.boundHashOps(CacheKey.CART_List).put(username,cartList);
        redisTemplate.boundHashOps(CacheKey.CART_List).expire(30,TimeUnit.DAYS);
    }

    @Override
    public int preferential(String username) {
        //获取选中的购物车 List<OrderItem> List<Map>
        List<OrderItem> orderItemList = findCartList(username).stream().
                filter(cart -> (boolean) cart.get("checked") == true).
                map(cart -> (OrderItem) cart.get("item")).collect(Collectors.toList());
        //按分类聚合统计每个分类的金额 group by
        Map<Integer, IntSummaryStatistics> cartMap = orderItemList.stream().
                collect(Collectors.groupingBy(OrderItem::getCategoryId3,
                        Collectors.summarizingInt(OrderItem::getMoney)));
        //循环结果，统计每个分类的优惠金额，并累加
        int allPreMoney = 0;
        //累计优惠金额
        for (Integer categoryId : cartMap.keySet()) {
            // 获取品类的消费金额
            int money = (int) cartMap.get(categoryId).getSum();
            int preMoney = preferentialService.findPreMoneyByCategoryId(categoryId, money);
            //获取优 惠金额
            System.out.println("分类：" + categoryId + " 消费金额：" + money + " 优 惠金额：" + preMoney);
            allPreMoney += preMoney;
        }
        return allPreMoney;
    }
}
